<template>
  <div class="game-type-container">
    <!-- 滚动容器 -->
    <div class="game-type-scroll-wrapper">
      <div class="game-type-scroll" ref="scrollContainer">
        <div
          v-for="(game, index) in games"
          :key="index"
          class="game-type-item"
          @click="selectGame(game)"
        >
          <img :src="game.imgsUrl" alt="" class="game-icon" />
          <span class="game-name">{{ game.gameTypeName }}</span>
        </div>
      </div>

      <!-- 滚动按钮 -->
      <button class="scroll-btn prev-btn" @click="scrollLeft">‹</button>
      <button class="scroll-btn next-btn" @click="scrollRight">›</button>
    </div>

    <div class="goods-container">
      <div class="search-box">
        <input
          type="text"
          placeholder="条件查询"
          class="search-input"
          @keyup.enter="search()"
          v-model="searchText"
        />
        <button class="search-btn" @click="search()">
          <i class="icon-search">🔍</i>
        </button>
      </div>
      <div
        v-if="goodsList.length > 0"
        class="goods-list"
        :style="{
          gridTemplateColumns: `repeat(auto-fit, minmax(200px, 1fr))`,
        }"
      >
        <div
          v-for="(good, index) in goodsList"
          :key="index"
          class="goods-item"
          @click="handleGoodsClick(good)"
        >
          <div class="goods-avatar">
            <img :src="good.imgsUrl" alt="" class="avatar-img" />
            <div class="audio-waveform"></div>
          </div>
          <div class="goods-info">
            <div class="goods-name">{{ good.orderTitle }}</div>
            <div class="goods-tag-price">
              <span class="goods-tag">{{
                getGameNameById(good.gameTypeId)
              }}</span
              ><span class="goods-price"
                >{{ good.orderPrice }}元/{{
                  good.orderUnit == 0 ? "局" : "小时"
                }}</span
              >
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <div class="empty-text">暂无商品信息</div>
      </div>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-size="12"
      layout="total, prev, pager, next"
      :total="this.total"
    >
    </el-pagination>

    <!-- 商品详情弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="selectedGood ? selectedGood.orderTitle : ''"
      width="500px"
      @close="handleDialogClose"
    >
      <div v-loading="loadingDetail" element-loading-text="加载中...">
        <div v-if="selectedGood" class="goods-detail">
          <!-- 图片轮播组件 -->
          <div class="image-slider">
            <el-carousel
              v-if="selectedGood.imgs && selectedGood.imgs.length > 0"
              trigger="click"
              height="300px"
              :autoplay="true"
              :interval="3000"
              indicator-position="outside"
            >
              <el-carousel-item
                v-for="(img, index) in selectedGood.imgs"
                :key="index"
              >
                <img :src="img.url" alt="" class="carousel-img" />
              </el-carousel-item>
            </el-carousel>

            <div v-else-if="selectedGood.imgsUrl" class="single-image">
              <img :src="selectedGood.imgsUrl" alt="" class="detail-img" />
            </div>
          </div>
          <div class="goods-detail-info">
            <div class="detail-name">{{ selectedGood.orderTitle }}</div>
            <div class="detail-price">
              价格: {{ selectedGood.orderPrice }}元/{{ selectedGood.orderUnit == 0 ? "局" : "小时" }}
            </div>
            <div class="detail-game">
              游戏类型: {{ getGameNameById(selectedGood.gameTypeId) }}
            </div>
          </div>
          <div class="quantity-selector">
            <span>购买数量:</span>
            <el-input-number
              v-model="orderQuantity"
              :min="1"
              :max="99"
              size="small"
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmOrder">确定下单</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bossApi from "@/http/bossApi";
export default {
  data() {
    return {
      tenantId: 1,
      currentPage: 1,
      pageSize: 12,
      total: 0,
      games: [],
      goodsList: [],
      selectedGame: null,
      searchText: "",
      // 添加弹窗相关数据
      dialogVisible: false,
      selectedGood: null,
      orderQuantity: 1,
      currentImageIndex: 0,
      loadingDetail: false,
    };
  },
  methods: {
    search() {
      bossApi
        .getGoodsList({
          tenantId: this.tenantId,
          gameTypeId: this.selectedGame,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.searchText,
        })
        .then((res) => {
          if (res.code == 200) {
            this.goodsList = res.data.list;
            this.total = res.data.count;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // ... 其他方法保持不变
    handleDialogClose() {
      // 关闭弹窗时的清理工作
      this.selectedGood = null;
      this.orderQuantity = 1;
    },

    confirmOrder() {
      // 确认下单逻辑
      console.log("下单信息:", {
        good: this.selectedGood,
        quantity: this.orderQuantity,
        totalPrice: this.selectedGood.orderPrice * this.orderQuantity,
      });
      // 这里可以添加实际的下单逻辑
      this.$message.success("下单成功!");
      this.dialogVisible = false;
    },
    scrollRight() {
      const container = this.$refs.scrollContainer;
      container.scrollLeft += 200;
    },
    scrollLeft() {
      const container = this.$refs.scrollContainer;
      container.scrollLeft -= 200;
    },
    selectGame(game) {
      this.selectedGame = game.id;
      this.getGoodsList();
    },
    // 向后端请求商品详细信息
    handleGoodsClick(good) {
      this.loadingDetail = true;
      bossApi
        .getGoodsInfoById({
          tenantId: this.tenantId,
          id: good.id,
        })
        .then((res) => {
          if (res.code == 200) {
            const goodsData = res.data;
            // 处理图片数据，确保 imgs 是一个包含 url 的数组
            console.log("goodsData:", goodsData);
            if (goodsData.imgs && Array.isArray(goodsData.imgs)) {
              // 确保每个图片对象都有url属性且为有效值
              goodsData.imgs = goodsData.imgs.filter(
                (img) => img && (img.url || img.imgsUrl)
              );
              // 标准化图片对象格式
              goodsData.imgs = goodsData.imgs.map((img) => ({
                url: img.url || img.imgsUrl,
              }));
            }
            this.selectedGood = goodsData;
            this.orderQuantity = 1;
            this.dialogVisible = true;
          } else {
            this.$message.error(res.message || "获取商品详情失败");
          }
        })
        .catch((error) => {
          this.$message.error("网络错误，请重试");
          console.error("获取商品详情失败", error);
        })
        .finally(() => {
          this.loadingDetail = false;
        });
    },
    getAllGameType() {
      // 获取全部游戏类型
      bossApi
        .getAllGameType({
          tenantId: this.tenantId,
        })
        .then((res) => {
          if (res.code != 200) {
            this.$message.error(res.message);
            return;
          }
          this.games = res.data;
        });
    },

    // 当前页改变时触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData(); // 重新请求数据
    },
    // 添加搜索方法
    performSearch() {
      this.currentPage = 1; // 重置页码
      this.getGoodsList(); // 执行搜索
    },
    // 获取业务数据的方法（示例）
    getGoodsList() {
      // 获取商品列表
      bossApi
        .getGoodsList({
          tenantId: this.tenantId,
          gameTypeId: this.selectedGame,
          pageNum: this.currentPage,
          pageSize: 12,
          search: this.searchText ? this.searchText : null,
        })
        .then((res) => {
          if (res.code == 200) {
            this.goodsList = res.data.list;
            this.total = res.data.count;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 正确的计算属性定义
    getGameNameById(id) {
      const game = this.games.find((g) => g.id === id);
      return game ? game.gameTypeName : "未知游戏";
    },
  },

  created() {
    // 获取路由查询参数中的 searchText
    this.searchText = this.$route.query.searchText || "";
    // 如果需要，可以调用搜索方法
    if (this.searchText) {
      this.performSearch();
    }
    // 页面刷新后清除URL中的搜索参数
    if (this.$route.query.searchText) {
      this.$router.replace({
        query: { ...this.$route.query, searchText: undefined },
      });
    }
    //加载全部游戏类型
    this.getAllGameType();
    this.getGoodsList();
    this.getGameNameById();
  },
};
</script>

<style scoped>
.image-slider {
  margin-bottom: 20px;
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.single-image {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.detail-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
}
.goods-detail {
  padding: 20px 0;
}

.goods-detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.detail-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
}

.goods-detail-info {
  flex: 1;
}

.detail-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
}

.detail-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: 700;
  margin-bottom: 5px;
}

.detail-game {
  font-size: 14px;
  color: #666;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 0;
  border-top: 1px solid #eee;
}

.dialog-footer {
  text-align: right;
}
/* 商品容器样式 */
.goods-container {
  width: 100%;
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  height: auto;
}
/* 商品项样式 */
/* 修改商品列表样式 */
.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}
.goods-item {
  padding: 20px;
  background-color: rgb(212, 147, 147);
}
/* 鼠标悬停时，商品项添加阴影和Y轴偏移 */
.goods-item:hover {
  transform: translateY(-5px);
}
/*  商品项图片样式 */
.avatar-img {
  width: 150px;
  height: 150px;
  object-fit: cover;
}

/* 滚动容器 */
.game-type-scroll-wrapper {
  position: relative;
  width: 100%;
}

/* 商品项名称样式 */
.goods-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/*  商品项价格样式 */
.goods-tag-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-tag {
  background: #e6f7ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}
/*  */
.goods-price {
  font-size: 16px;
  font-weight: 700;
  color: #ff4d4f;
}
/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-text {
  color: #999;
  font-size: 16px;
}

.pagination {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.game-type-container {
  position: relative;
  width: 100%;
  overflow: hidden;
  background-color: #ede5ed;
  padding: 10px 0;
}

.game-type-scroll {
  display: flex;
  gap: 15px;
  overflow-x: auto;
  scroll-behavior: smooth;
  padding: 0 40px; /* 为按钮留出空间 */
  white-space: nowrap;
}

.game-type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.game-type-item:hover {
  transform: scale(1.05);
}

.game-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  object-fit: cover;
}

.game-name {
  font-size: 14px;
  color: #fff;
  margin-top: 5px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 60px;
}

.scroll-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  z-index: 100; /* 提高z-index确保可见 */
}
.prev-btn {
  left: 10px;
}

.next-btn {
  right: 10px;
}
</style>
